﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace ConvertToExcel
{
    public partial class Main : Form
    {
        private string TemplateDir = Directory.GetCurrentDirectory() + @"\Template\";
        private ExcelImpl excelImpl=new ExcelImpl();
        private IList<Part> PartList;

        public Main()
        {
            InitializeComponent();
            InitForm();
            excelImpl.noticeMessage += new NoticeMessage(PrintMessge);
            CsvHelper.noticeMessage += new NoticeMessage(PrintMessge);
        }

        private void InitForm()
        {
            if (Directory.Exists(TemplateDir))
            {
                string[] TempPaths = Directory.GetFiles(TemplateDir);
                this.cmbTemplete.Items.AddRange(TempPaths.Select(m => m.Replace(TemplateDir, "")).ToArray());
                this.cmbTemplete.SelectedIndex = 0;
                this.PrintMessge(String.Format("载入模板：{0},{1}", this.cmbTemplete.Items[0], this.cmbTemplete.Items[1]));
                this.notifyicon.Visible = true;
                this.notifyicon.ContextMenuStrip = contextMenuStrip;
            }
            else
            {
                MessageBox.Show("缺失模板文件夹！","Error");
            }
        }

        // 界面浏览按钮事件的响应
        private void btn_OpenFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Csv文件(*.csv)|*.csv";
            if (ofd.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }
            this.txt_Path.Text = ofd.FileName;
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(this.txt_Path.Text))
            {
                PrintMessge("warn：未选择目标文件");
                MessageBox.Show("请选择目标源(csv文件)！","警告");
                return;
            }
            var data = CsvHelper.Read<Part>(this.txt_Path.Text, new CsvParams(true, ',', Encoding.Default, "zh-CN"));
            PartList = CsvHelper.Filter(data, this.txtPartName.Text);
            if (PartList != null)
                PrintMessge(String.Format("查询结果：共{0}条记录", PartList.Count));
            else
                PrintMessge("error: 查询出错！");
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(this.cmbTemplete.Text))
            {
                PrintMessge("warn：未选择模板文件");
                return;
            }
            if (PartList == null)
            {
                PrintMessge("warn: 未执行查询操作");
                return;
            }
            SaveFileDialog SaveFile = new SaveFileDialog() { Filter = "Excel文件(*.xls)|*.xls|Csv文件(*.csv)|*.csv" };
            if (SaveFile.ShowDialog() == DialogResult.OK)
            {
                if (this.IsFileInUse(SaveFile.FileName))
                {
                    PrintMessge("info：需要替换的文件被占用");
                    MessageBox.Show("请先关闭保存的文件！");
                    return;
                }
                bool flag = false;
                if (cmbTemplete.SelectedIndex==0)
                {
                   flag= excelImpl.ExporExcel(PartList,TemplateDir+this.cmbTemplete.Text , SaveFile.FileName,ExcelTemp.TempAB);
                }
                else if (cmbTemplete.SelectedIndex == 1)
                {
                   flag= excelImpl.ExporExcel(PartList, TemplateDir + this.cmbTemplete.Text, SaveFile.FileName, ExcelTemp.TempC);
                }

                if (flag)
                {
                    PrintMessge("导出成功,路径:" + SaveFile.FileName);
                }
            }
        }

        public void PrintMessge(string msg)
        {
            if (!String.IsNullOrEmpty(msg))
            {
                //this.Invoke(new MethodInvoker(delegate() { this.listBox1.Items.Add(msg); }));
                this.listBox1.Items.Add(msg);
            }
        }

        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Hide();
        }
         
        private void notifyicon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.Visible)
            {
                this.Hide();
            }
            else
            {
                this.Show();
                WindowState = FormWindowState.Normal;
                this.Activate();
            }
        }

        private void ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var Target = sender as ToolStripMenuItem;
            switch (Target.Name)
            {
                case "showMenuItem":
                    this.Show();
                    WindowState = FormWindowState.Normal;
                    this.Activate();
                    break;
                case "hideMenuItem":
                    this.Hide();
                    break;
                case "exitMenuItem":
                    this.Close();
                    this.Dispose();
                    Application.Exit();
                    break;
            }
        }

        private bool IsFileInUse(string filename)
        {
            bool locked = false;
            FileStream fs = null;
            try
            {
                fs =
                     File.Open(filename, FileMode.OpenOrCreate,
                     FileAccess.ReadWrite, FileShare.None);
            }
            catch (IOException)
            {
                locked = true;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }
            return locked;
        }
    }
}
